package org.bjf.config.ds;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.enums.IdType;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import javax.sql.DataSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

@Configuration
@MapperScan(basePackages = UserDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "userSessionFactory")
public class UserDataSourceConfig {

  static final String PACKAGE = "org.bjf.modules.user.mapper";
  private static final String MAPPERLOCATIONS = "classpath*:mapper/user/**/*.xml";
  private static final String TYPEALIASESPACKAGE = "org.bjf.modules.user.bean";

  @Bean(name = "userDataSource")
  @ConfigurationProperties(prefix = "custom.datasource.user")
  @Primary
  public DataSource dataSource() {
    return new DruidDataSource();
  }

  @Bean(name = "userTransactionManager")
  @Primary
  public DataSourceTransactionManager transactionManager(
      @Qualifier("userDataSource") DataSource dataSource) {
    return new DataSourceTransactionManager(dataSource);
  }

  @Bean(name = "userSessionFactory")
  @Primary
  public SqlSessionFactory sessionFactory(
      @Qualifier("userDataSource") DataSource dataSource) throws Exception {

    //===1.mybatis-plus globalConfig配置
    GlobalConfiguration globalConfig = new GlobalConfiguration();
    // 字段的驼峰下划线转换
    globalConfig.setDbColumnUnderline(Boolean.TRUE);
    globalConfig.setIdType(IdType.AUTO.getKey());

    //===2.构造sessionFactory(mybatis-plus)
    final MybatisSqlSessionFactoryBean sf = new MybatisSqlSessionFactoryBean();
    sf.setDataSource(dataSource);
    sf.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPERLOCATIONS));
    sf.setTypeAliasesPackage(TYPEALIASESPACKAGE);
    sf.setGlobalConfig(globalConfig);
    // 分页插件
    sf.setPlugins(new Interceptor[]{new PaginationInterceptor()});

    return sf.getObject();
  }
}  